package handler

//处理的结果
import (
	"encoding/json"
	"fmt"
	"ginProject/biz/dao"
	"ginProject/biz/model"
	"ginProject/biz/service"
	"ginProject/biz/utils"
	"ginProject/biz/vo"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

/**
 * @Author leibidong
 * @Description 登录验证handler层
 * @Date  2021/7/11 17:35
 **/
func LoginHandler(c *gin.Context) {
	var login vo.Login
	c.ShouldBind(&login)
	fmt.Println(login)
	var t = service.UserLogin(login.LoginName, login.Password)
	if t != 0 {
		uuid := utils.GetUUid()
		c.SetCookie("token", uuid, 86400, "/", "localhost", false, false)
		login := model.LoginToken{Token: uuid, Status: 1, ID: t, Expired: time.Now().String()}
		redisKey := utils.GetRedisLoginToken(uuid)
		rdb := dao.InitRedis()
		var ub []byte
		ub, err := json.Marshal(login)
		if err != nil {
			fmt.Printf("%s\n", err.Error())
		}
		rdb.Set(redisKey, ub, 86400*time.Second)
		utils.ReturnOKMessage(t, c)
	} else {
		utils.ReturnFailureMessage(c, nil)
	}
}

/**
 * @Author leibidong
 * @Description 退出登录handler层
 * @Date  2021/7/11 17:35
 **/
func LogoutHandler(c *gin.Context) {
	s := c.Query("id")
	id, _ := strconv.Atoi(s)
	status := service.UserLogout(id)
	if status == 1 {
		cookie, _ := c.Cookie("token")
		redisKey := utils.GetRedisLoginToken(cookie)
		rdb := dao.InitRedis()
		rdb.Del(redisKey)
		utils.ReturnOKMessage("ok", c)
	} else {
		utils.ReturnFailureMessage(c, nil)
	}
}
